<?php
namespace app\workerman;

use app\common\entity\GameLoginLog;
use GatewayWorker\Lib\Gateway;
use app\workerman\Game;
use app\workerman\Robot;
use app\common\entity\User;

class Events
{



    public $pingInterval = 0;
    public static function onWorkerStart($businessWorker){

        echo "onWorkerStart\n";
        $game = new Game();
        $game->workerStart();
        $robot = new Robot();
        $robot->robotRandIn();
    }

    public static function onConnect($client_id){
        echo "onConnect\n";
    }

    public static function onWebSocketConnect($client_id, $data){
        echo "onWebSocketConnect\n";
    }

    public static function onMessage($client_id, $message){


        $data = json_decode($message, true);

        if(!$data && !Gateway::isOnline($client_id))
        {
            return false;
        }

        $game = new Game();

        // 根据类型执行不同的业务
        if(isset($data['token'])){
            $userId = self::getUserId($data['token']);
            if(!$userId){
                Gateway::sendToClient($client_id,errorSend('login',10,'登陆信息错误，请登陆'));
                return false;
            }
        }else{
            return false;
        }
        switch($data['type']) {
            // 客户端回应服务端的心跳
            case 'pong':
                break;
            // 客户端登录 message格式: {type:login, uid:xx} ，添加到客户端
            case 'login':

                $game->login($client_id,$userId,$data['ordersn'],$data['token']);
                break;
            case 'roomin':
                $game->RoomIn($client_id,$data['room_id']);
                break;
            case 'roomout':
                $game->inRoomOut($client_id,$data['room_id']);
                break;
            case 'focas':
                $game->focas($client_id,$data['room_id'],$data['status']);
                break;
            default:

        }

    }

    //判断是否登录
    static public function getUserId($token)
    {
        $userId = User::where('login_time', $token)->value('id');
        return $userId;
    }
    public static function onClose($client_id){
        echo "onClose\n";
        $loginInfo = GameLoginLog::where('client_id',$client_id)->order('id desc')->find();
        echo $loginInfo['user_id']."\n";
        $game = new Game();
        $game->RoomOut($client_id);

    }
}